package thread;

/**
 * 当多个线程并发操作同一界面资源，由于线程切换时机不确定，导致操作顺序出现了混乱。
 */
public class SyncDemo1 {
    public static void main(String[] args) {
        Test test = new Test();

        Thread t1 = new Thread(){
            public void run(){
            while (true){
                int num = test.getBean();
                Thread.yield();
                System.out.println(getName()+"取了第"+num);

            }
            }
        };
        Thread t2 = new Thread(){
            public void run(){
             while (true) {
                 int num = test.getBean();
                 Thread.yield();
                 System.out.println(getName()+"取了第"+num);
             }
            }
        };
        t1.start();
        t2.start();
    }

}
 class Test{
    private int bean=20;
    public synchronized int getBean(){
        if(bean==0){
            throw new RuntimeException("没有豆子了");
        }
        Thread.yield();
        return bean--;
    }
}
